from ui.hat_widget import HatPopup
from kivy.lang import Builder

Builder.load_string('''
<ScrollPopup>:
    scroll_layout: scroll_layout
    label: label
    BoxLayout:
        orientation: 'vertical'
        ScrollView:
            do_scroll_x: False
            size_hint_y: 1
            GridLayout:
                id: scroll_layout
                cols: 1
                size_hint_y: None
                height: root.label.texture_size[1]
                FittableLabel:
                    size_hint_y: None
                    height: self.texture_size[1]
                    size_hint_x: 1
                    id: label
                    #fit_height: False
                    text: root.info
        FittableButton:
            text: _(u'OK')
            size_hint_y: None
            height: root.height / 9
            on_release: root.dismiss()
''')


def open_scroll_popup(title, text, widget):
    size = 0
    MAX_SIZE = 25
    res_text = ''
    for word in text.split(' '):
        if size + len(word) >= MAX_SIZE:
            res_text += '\n'
            size = len(word)
        else:
            res_text += ' '
            size += len(word) + 1
        res_text += word

    popup = ScrollPopup(res_text, res_text.count('\n'), title=title,
                        size_hint=(None, None),
                        size=(widget.width / 1.5, widget.height / 1.5))
    popup.open()


class ScrollPopup(HatPopup):
    def __init__(self, text, line_count, **kwargs):
        self.info = text
        self.line_count = line_count
        super(ScrollPopup, self).__init__(**kwargs)
